<?php
namespace xcom\model;
use x\Xbase;
use x\my\File;
class Attachment extends Xbase
{
    //上传图片
    public function upimg($dirs = '', $width = 0, $height=0){
        if(c('api.is_upload_aliyun')){
            return $this->upimgtoaliyun();
        }
        $file = $_FILES['file']['tmp_name'];
        $image = \think\Image::open($file);
        if(in_array($image->type(),['jpg','jpeg','png','gif'])){
            $ip = ip();
            if($dirs){
              $dir = APP_PATH.'../public/uploads/'.$dirs.'/'.date('Y').'/'.date('m').'/'.date('d').'/';
            }else{
              $dir = APP_PATH.'../public/uploads/images/'.date('Y').'/'.date('m').'/'.date('d').'/';
            }
            $filename = $dir.token($ip).".".$image->type();
            if (!is_dir(dirname($filename))) {
                if(!com_mkdir(dirname($filename))){
                    die('Without directory permissions, upload images fail');
                }
            }
            if($width==0 && $height==0){
              $image->save($filename);
            }else{
              //验证宽高比
              $width  = $width ? $width: $image->width();
              $height = $height ? $height: $image->height();
              // if($width/$height > 1920/400){
              //     $this->setError('宽高比不能大于: 1920/400','file');
              //     return false;
              // }
              $image->thumb($width,$height)->save($filename);
            }
            $arr = explode('uploads',$filename);
            $url = "/uploads/".$arr[1];
            $data=[
                'url'=>$url,
                'ip' =>$ip,
                'create_time'=>time(),
            ];
            $this->db->insert('attachment',$data);
            return $url;
        }else{
            $this->setError('只能上传图片格式为:jpg|jpeg|png|gif','file');
            return false;
        }
    }
    //上传图片
    function upimgtoaliyun(){
        $aly_oss_keyid     = c('api.aly_oss_keyid');
        $aly_oss_keysecret = c('api.aly_oss_keysecret');
        $aly_oss_endpoint  = c('api.aly_oss_endpoint');
        $aly_oss_bucket    = c('api.aly_oss_bucket');

        $file = date("ymd")."_".time()."_".rand(10000,99999).".jpg";
        $oss=new \OSS\OssClient($aly_oss_keyid,$aly_oss_keysecret,$aly_oss_endpoint);
        $oss->uploadFile($aly_oss_bucket,$file,$_FILES['file']['tmp_name']);

        $url = "http://{$aly_oss_bucket}.{$aly_oss_endpoint}/".$file;
        $data=[
          'url'=>$url,
          'ip' =>ip(),
          'create_time'=>time(),
        ];
        $this->db->insert('attachment',$data);
        return $url;
    }

    /**
     * 确认上传的图片
     * @param  [type] $table    [description]
     * @param  [type] $table_id [description]
     * @param  [type] $d        [description]
     * @return [type]           [description]
     */
    function imgSure($table,$table_id,$d){
        //本次上传的图片
        $temp = $this->getPic($d);
        //删除无用图片
        $this->imgDel($table,$table_id,$temp);

        //确认本次上传
        if($temp){
            $vars = [$table,$table_id,time()];
            $w = "";
            foreach($temp as $v){
                $w .= "or url=? ";
                $vars[] = $v;
            }
            $w = ltrim($w,'or');
            $w = " where ($w) and `table`=''";
            $sql = "update attachment set `table`=?,`table_id`=?,`update_time` = ?,`status`=1 $w";
            $this->db->query($sql,$vars);
        }
    }
    /**
     * 删除无用图片
     * @param  [type] $table    [表名称]
     * @param  [type] $table_id [表id]
     * @return [type]           [description]
     */
    public function imgDel($table,$table_id, $pic=[]){
        //把图片设置为可删除
        $map = [];
        $map[] = ['and','type','=',0];
        $map[] = ['and','table','=',$table];
        $map[] = ['and','table_id','=',$table_id];
        if($pic!==true){
            foreach($pic as $v){
                $map[] = ['and','url','!=',$v];
            }
        }
        $w = where($map);
        $this->db->query("update attachment set `status`=2 $w[0]",$w[1]);

        //把过期图片设置为可删除
        $time = time()-60*60*3;
        $this->db->query('update attachment set `status`=2 where `type`=0 and (`status`=0 and `create_time`<?)',[$time]);
        $rs = $this->db->query('select id,url from attachment where `type`=0 and `status`=2');
        foreach($rs as $v){
            $this->db->delete('attachment',$v['id']);
            $result = $this->db->select('attachment',['url=?',[$v['url']]]);
            if(!$result){
                @unlink(APP_PATH.'../public'.$v['url']);
            }
        }
    }
    /**
     * 复制图片地址
     * @param  [type] $table    [description]
     * @param  [type] $table_id [description]
     * @return [type]           [description]
     */
    public function imgCopy($table,$table_id,$d){
        //本次上传的图片
        $temp = $this->getPic($d);
        if($temp){
            $data = [];
            foreach($temp as $v){
                $data[] = [
                    'table' => $table,
                    'table_id' => $table_id,
                    'url' => $v,
                    'ip' => ip(),
                    'status' => 1,
                ];
            }
            $this->db->insertAll('attachment',$data);
        }
    }

    /**
     * 获取内容图片
     * @param  [type] $d [post内容]
     * @return [type]    [description]
     */
    public function getPic($d){
        $temp = [];
        foreach($d as $k => $v){
            //单图
            if( ($k=='pic' || strpos($k, 'pic_')!==false) && $v){
                $temp[] = $v;
            //多图
            }elseif( ($k=='pics' || strpos($k, 'pics_')!==false)  && $v){
                $temp = array_merge($temp,explode(',',$v));
            }elseif($k=='content'){
                $v = strtolower(htmlspecialchars_decode($v));
                $preg = '/<img.*?src=[\"|\']?\/uploads(.*?)[\"|\'].*?[\/]?>/i';
                preg_match_all($preg, $v, $imgArr);
                if(isset($imgArr[1])){
                    foreach($imgArr[1] as $img){
                        $temp[] = "/uploads".$img;
                    }
                }
                //layui编辑器
                $preg = '/img\[\/uploads(.*?)\]/i';
                preg_match_all($preg, $v, $imgArr);
                if(isset($imgArr[1])){
                    foreach($imgArr[1] as $img){
                        $temp[] = "/uploads".$img;
                    }
                }
            }
        }
        $temp = array_filter($temp);
        return $temp;
    }
}
